/**
 *
 * Copyright (C) 2008  Igor Vdovichenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * Though a sincere effort has been made to deliver a professional,
 * quality product,the library itself is distributed WITHOUT ANY WARRANTY;
 * See the GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 */
package com.vin.scriptutils.utils;

import com.vin.scriptutils.UString;
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 *
 * @author igor
 */
public class ScriptTextProvider {

    private final String pathToScripts;

    /**
     * ScriptTextProvider()
     * @param pathToScripts Path so scripts, i.e. "/com/company/product/module/scripts".
     * Couldn't be <code>null</code>.
     *
     */


    public ScriptTextProvider(final String pathToScripts) {
        this.pathToScripts = pathToScripts;
    }


    public String getScriptText(final String scriptFileName) throws IOException {
        final InputStream resourceStream = getScriptStream(scriptFileName);
        if (resourceStream == null) {
            return null;
        }

        final BufferedReader reader = new BufferedReader(new InputStreamReader(resourceStream));
        final StringBuffer result = new StringBuffer();
        try {
            String line = reader.readLine();
            result.append(line);
            while (true) {
                line = reader.readLine();
                if (line == null) {
                    break;
                }
                result.append(UString.UNIX_LINE_SEPARATOR);
                result.append(line);
            }

        } finally {
            closeResource(resourceStream);
            reader.close();
        }
        return result.toString();
    }

    public InputStream getScriptStream(final String scriptName) {
        String resourceName = this.pathToScripts + UString.FILE_SEPARATOR + scriptName;
        InputStream resourceStream = getClass().getResourceAsStream(resourceName);
        return resourceStream;
    }

    private static void closeResource(final Closeable closeable) throws IOException {
        closeable.close();
    }
}
